package com.deyuanyun.pic.settings.service.prvlg.impl;

import com.deyuanyun.pic.common.tool.JXL;
import com.deyuanyun.pic.common.util.DateUtil;
import com.deyuanyun.pic.common.util.ObjectUtil;
import com.deyuanyun.pic.common.util.web.Asserts;
import com.deyuanyun.pic.settings.controller.dto.UserSessionVO;
import com.deyuanyun.pic.settings.controller.dto.prvlg.UserExportVO;
import com.deyuanyun.pic.settings.controller.dto.prvlg.UserVO;
import com.deyuanyun.pic.settings.domain.org.OrgInfo;
import com.deyuanyun.pic.settings.domain.prvlg.CustomUser;
import com.deyuanyun.pic.settings.domain.prvlg.User;
import com.deyuanyun.pic.settings.domain.prvlg.UserExpand;
import com.deyuanyun.pic.settings.domain.prvlg.UserImpVO;
import com.deyuanyun.pic.settings.mapper.prvlg.CustomUserMapper;
import com.deyuanyun.pic.settings.mapper.prvlg.UserExpandMapper;
import com.deyuanyun.pic.settings.mapper.prvlg.UserGroupMapper;
import com.deyuanyun.pic.settings.mapper.prvlg.UserMapper;
import com.deyuanyun.pic.settings.service.prvlg.UserService;
import com.deyuanyun.pic.settings.support.cache.SessionCacheSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {
	//未删除
	private static final short UNDELETE = 0;
	//已删除
	private static final short DELETE = 1;
	//邮件认证[0:未认证 1：已认证]
	private static final short ISEMAIL = 0;
	//手机认证[0:未认证 1：已认证]
	private static final short ISMOBILE = 0;
	//锁定
	private static final String LOCKED="LOCKED";
	//激活
	private static final String ACTIVATE="ACTIVATE";
	//装载解析excel的错误信息
	private StringBuffer errStr; 
	//校验excel信息是否通过：
	private boolean isPass = false;
	@Resource
	UserMapper userMapper;
	@Autowired
	CustomUserMapper customUserMapper;

	@Resource
	private UserExpandMapper userExpandMapper;
	@Resource
	private UserGroupMapper userGroupMapper;
	
	public int deleteByPrimaryKey(BigDecimal id) {
		// TODO Auto-generated method stub
		return 0;
	}

    public int deleteByPrimaryKey(String id) {
        return 0;  //To change body of implemented methods use File | Settings | File Templates.
    }

    public int insert(User record) {
		// TODO Auto-generated method stub
		return 0;
	}

	public int insertSelective(User record) {
		// TODO Auto-generated method stub
		return 0;
	}

    public User selectByPrimaryKey(String id) {
        return null;  //To change body of implemented methods use File | Settings | File Templates.
    }

    public User selectByPrimaryKey(BigDecimal id) {
		// TODO Auto-generated method stub
		return null;
	}

	public int updateByPrimaryKeySelective(User record) {
		return userMapper.updateByPrimaryKeySelective(record);
	}

	public int updateByPrimaryKey(User record) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public List<CustomUser> getUser(String userName) {
		Map map=new HashMap();
		map.put("userName",userName);
		return customUserMapper.queryUserInfo(map);
	}

	@Override
	public List<OrgInfo> selectAllCompany() {
		return userMapper.selectAllCompany();
	}

	@Override
	public List<OrgInfo> selectDepartmentByCompanyId(String companyId) {
		return userMapper.selectDepartmentByCompanyId(companyId);
	}

	@Override
	public List<OrgInfo> selectPositionByDepartmentId(String departmentId) {
		return userMapper.selectPositionByDepartmentId(departmentId);
	}

	@Override
	public int save(String username, String moblie, String email, String realName, String sex, String code,
			String companyId, String departmentId, String positionId, String state,String remark,String userId) {
		int i = 0;
		UserSessionVO uv = SessionCacheSupport.getSessionVO();
		Map<String,Object> praMap = new HashMap<String,Object>();
		praMap.put("username", username);
		praMap.put("userId", userId);
		String oUserName = userMapper.selectUserByUsername(praMap);
		
		praMap.put("moblie", moblie);
		User u1 = userMapper.selectUserByMobile(praMap);
		praMap.put("email", email);
		User u2 = userMapper.selectUserByEmail(praMap);
		
		if(null != oUserName ){
			Asserts.assertTrue(false, "用户名称已经存在，请重新输入");
		}else if(ObjectUtil.isNotNullEmpty(u1)){
			Asserts.assertTrue(false, "手机号已经存在，请重新输入");
		}else if(ObjectUtil.isNotNullEmpty(u2)){
			Asserts.assertTrue(false, "邮箱已经存在，请重新输入");
		}else if(StringUtils.isEmpty(userId)){
			User user = new User();
//			user.setCreateDate(DateUtil.getCurrentDate());
			user.setUsername(username);
			user.setEmail(email);
			user.setMoblie(moblie);
			user.setDeleted(UNDELETE);
			user.setIsEmail(ISEMAIL);
			user.setIsMobile(ISMOBILE);
			user.setCreateRemark(remark);
			user.setState(state);
			//初始密码为111111
			user.setPwd(encodePassword(username,"111111"));
			user.setCreateUser(uv.getId());
			i += userMapper.insertSelective(user);

			UserExpand ue = new UserExpand();
			ue.setDeleted(UNDELETE);
			ue.setCreateDate(DateUtil.getCurrentDate());
			ue.setEmpNo(code);
			ue.setRealName(realName);
			ue.setEmail(email);
			ue.setMobile(moblie);
			ue.setCompanyId(companyId);
			ue.setDeptId(departmentId);
			ue.setPostId(positionId);
			ue.setUserId(user.getId());
			ue.setSex(sex);
			ue.setCreateUser(uv.getId());
			i += userExpandMapper.insertSelective(ue);
		}else{
			User user = userMapper.selectByPrimaryKey(userId);
			user.setUpdateDate(DateUtil.getCurrentDate());
			user.setUsername(username);
			user.setEmail(email);
			user.setMoblie(moblie);
			user.setCreateRemark(remark);
			user.setState(state);
			user.setCreateUser(uv.getId());
			i += userMapper.updateByPrimaryKeySelective(user);
			UserExpand ue = userExpandMapper.selectUserExpandByUserId(userId);
			if(ue != null) { //内置账号没得用户扩展信息，这里需判断是否为空
				ue.setUpdateDate(DateUtil.getCurrentDate());
				ue.setEmpNo(code);
				ue.setRealName(realName);
				ue.setEmail(email);
				ue.setMobile(moblie);
				ue.setCompanyId(companyId);
				ue.setDeptId(departmentId);
				ue.setPostId(positionId);
				ue.setSex(sex);
				ue.setCreateUser(uv.getId());
				i+= userExpandMapper.updateByPrimaryKeySelective(ue);
			}
		}
		return i;
	}

	@Override
	public List<UserVO> getUserManagerIndex(Map<String, Object> map) {
		return userMapper.getUserManagerIndex(map);
	}

	@Override
	public int changeState(String userId, String state) {
		int i = 0;
		User user = userMapper.selectByPrimaryKey(userId);
		if(null != user){
			user.setState(state);
			i = userMapper.updateByPrimaryKeySelective(user);
		}
		return i;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public Map<String, Object> userAuthorize(String id) {
		Map<String,Object> map = new HashMap<String,Object>();
		Map<String,Object> praMap = new HashMap<String,Object>();
		praMap.put("mark", "");
		List allUserGroup = userGroupMapper.selectAllUserGroup(praMap);
		if(id.indexOf(",") >=0){
			map.put("ug", allUserGroup);
		}else{
			//查询该用户已经配置了的用户组
			List<String> userGroup = userMapper.selectUserGroupByUserId(id);
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < userGroup.size(); i++) {
				if (i == userGroup.size() - 1) {
					sb.append(userGroup.get(i));
				} else {
					sb.append(userGroup.get(i)).append(",");
				}
			}
			map.put("ug", allUserGroup);
			map.put("userGroup", sb.toString());
		}
		return map;
	}

	@Override
	public int saveAuthorize(String id,String[] data) {
		int i = 0;
		String[] idArr = id.split(",");
		for (String userId : idArr) {
			//删除该用户所属的原来的用户组
			i = userMapper.deleteAuthorize(userId);
			for (String userGroupId : data) {
				if(!StringUtils.isEmpty(userGroupId)){
					Map<String,Object> map = new HashMap<String,Object>();
					map.put("id", UUID.randomUUID().toString().replace("-", ""));
					map.put("userId", userId);
					map.put("userGroupId", userGroupId);
					userMapper.saveAuthorize(map);
					i++;
				}
			}
		}
		return i;
	}

	@Override
	public int deleteData(String idStr) {
		int count = 0;
		String[] idArr = idStr.split(",");
		for (String id : idArr) {
			User user = userMapper.selectByPrimaryKey(id);
			if(null != user && LOCKED.equals(user.getState())){
				user.setDeleted(DELETE);
				userMapper.updateByPrimaryKeySelective(user);
				count ++;
			}
		}
		return count;
	}

	@Override
	public int dataOnOrOff(String idStr, String opt) {
		int count = 0;
		String[] idArr = idStr.split(",");
		if("on".equals(opt)){
			for (String id : idArr) {
				User user = userMapper.selectByPrimaryKey(id);
				if(LOCKED.equals(user.getState())){
					user.setState(ACTIVATE);
					userMapper.updateByPrimaryKeySelective(user);
					count ++;
				}
			}
		}
		if("off".equals(opt)){
			for (String id : idArr) {
				User user = userMapper.selectByPrimaryKey(id);
				if(ACTIVATE.equals(user.getState())){
					user.setState(LOCKED);
					userMapper.updateByPrimaryKeySelective(user);
					count ++;
				}
			}
		}
		return count;
	}

	@Override
	public List<UserVO> searchUser(String username, String company, String department,String isAuthorize) {
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("username", username);
		map.put("company", company);
		map.put("department", department);
		map.put("isAuthorize", isAuthorize);
		List<UserVO> list = userMapper.searchUser(map);
		return list;
	}

	@Override
	public UserVO queryUserExpById(String userId) throws Exception {
		if (ObjectUtil.isEmptyAll(userId)){
			return null;
		}
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("userId",userId);
		UserVO userVO = userMapper.searchUserDetail(map);
		if (ObjectUtil.isEmptyAll(userVO)){
			return new UserVO();
		}
		return userVO;
	}
	@Override
	public void updateSelfUserInfo(User user, UserExpand userExpand){
		UserSessionVO sessionVO= SessionCacheSupport.getSessionVO();
		if (user!=null){
			user.setId(sessionVO.getId());
			userMapper.updateByPrimaryKeySelective(user);
            sessionVO.setUserDetailInfo(null);
		}
		if (userExpand!=null){
            sessionVO.setUserDetailInfo(null);
			userExpandMapper.updateByPrimaryKeySelective(userExpand);
		}
		List<CustomUser>  userList = getUser(sessionVO.getUsername());
        com.deyuanyun.pic.settings.support.SecurityUtils.setUser(userList.get(0));//重新设置缓存中的UserSessionVO
	}

    @Override
    public UserExpand getUserExpand(String userId) {
        return userExpandMapper.selectUserExpandByUserId(userId);
    }

    @Override
	public List<String[]> exportData(UserVO uv) {
		List<List<String[]>> result = new ArrayList<List<String[]>>();
		List<LinkedHashMap<String, Object>> list = new ArrayList<LinkedHashMap<String, Object>>();
		list = userMapper.exportData(uv);
		if (list.size() == 0) {
			list = null;
		}
		//result.add(JXL.toList(list, "yyyy-MM-DD"));
		return JXL.toList(list, "yyyy-MM-DD");
	}

	
    /**
     * 密码加密工具
     * @param userName
     * @param pwd
     * @return
     */
    private static String encodePassword(String userName, String pwd) {
        String salt="_gas_pipe_";//加盐
        ShaPasswordEncoder messageDigestPasswordEncoder = new ShaPasswordEncoder(256);
        messageDigestPasswordEncoder.setEncodeHashAsBase64(true);
        return messageDigestPasswordEncoder.encodePassword(userName+pwd, salt);
    }

	@Override
	public int resetPwd(String idStr) {
		String[] ids = idStr.split(",");
		int count = 0;
		for (String id : ids) {
			User user = userMapper.selectByPrimaryKey(id);
			user.setPwd(encodePassword(user.getUsername(),"111111"));
			userMapper.updateByPrimaryKeySelective(user);
			count ++;
		}
		return count;
	}

	@Override
	public List<UserExportVO> exportUser(UserVO uv) {
		return userMapper.exportUser(uv);
	}

	@Override
	public void insertImpUser(List<UserImpVO> finalInfo) {
		int i = 0;
		UserSessionVO userSessionVO= SessionCacheSupport.getSessionVO();
		/*System.out.println("处理前>>>>"+finalInfo.size());
		//暂时考虑 只通过UserImpVO对象去重
		Set<UserImpVO> set = new HashSet<UserImpVO>();
		set.addAll(finalInfo);
		finalInfo.clear();
		finalInfo.addAll(set);
		System.out.println("处理后>>>>"+finalInfo.size());*/
		if(ObjectUtil.isNotNullEmpty(finalInfo)){
			for (UserImpVO userImp : finalInfo) {
				User user = new User();
				user.setUsername(userImp.getUsername());
				user.setEmail(userImp.getEmail());
				user.setMoblie(userImp.getMobile());
				user.setDeleted(UNDELETE);
				user.setIsEmail(ISEMAIL);
				user.setIsMobile(ISMOBILE);
				user.setCreateRemark(userImp.getRemark());
				user.setState(ACTIVATE);
				//初始密码为111111
				user.setPwd(encodePassword(userImp.getUsername(),"111111"));
				user.setCreateUser(userSessionVO.getId());
				userMapper.insertSelective(user);
				UserExpand ue = new UserExpand();
				ue.setDeleted(UNDELETE);
				ue.setCreateDate(DateUtil.getCurrentDate());
				ue.setEmpNo(userImp.getEmpNo());
				ue.setRealName(userImp.getRealName());
				ue.setEmail(userImp.getEmail());
				ue.setMobile(userImp.getMobile());
				OrgInfo company = userMapper.selectCompanyByCompanyName(userImp.getCompany());
				OrgInfo department = userMapper.selectDepartmentByDepartmentName(userImp.getDepartment());
				OrgInfo position = userMapper.selectPositionByPositionName(userImp.getPosition());
				ue.setCompanyId(company.getId());
				ue.setDeptId(department.getId());
				if(ObjectUtil.isNotNullEmpty(position)){
					ue.setPostId(position.getId());
				}
				ue.setUserId(user.getId());
				ue.setSex(userImp.getSex());
				ue.setCreateUser(userSessionVO.getId());
				i = userExpandMapper.insertSelective(ue);
			}
		}
	}

	@Override
	public List<UserVO> findList(Map<String, Object> map) {
		// TODO Auto-generated method stub
		return userMapper.findList(map);
	}
}
